import React, { useState, useEffect } from "react";
import { CalendarDay, MarketingTemplate, Festival } from "../../types/calendar";
import { getMonthDays } from "../../utils/calendar";
import styles from "./index.module.less";
import { Select } from "antd";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import Lunar from "lunar-javascript";

/**
 * 获取未来一个月内的所有节日和节气信息
 * 包含：
 * 1. 农历传统节日（如春节、元宵节等）
 * 2. 24节气（如立春、雨水等）
 * 3. 公历节日（如元旦、圣诞节等）
 * 
 * @returns {MarketingTemplate[]} 返回节日营销模板数组
 */
const getNextMonthFestivals = () => {
  const festivals: MarketingTemplate[] = [];
  // 获取今天的日期
  const today = new Date();
  // 计算一个月后的日期
  const nextMonth = new Date(today);
  nextMonth.setMonth(nextMonth.getMonth() + 1);

  // 遍历从今天到下个月这段时间的每一天
  for (const currentDate = new Date(today); currentDate <= nextMonth; currentDate.setDate(currentDate.getDate() + 1)) {
    // 获取当前日期的农历信息
    const lunar = Lunar.Solar.fromDate(currentDate).getLunar();
    
    // 获取农历节日（如春节、元宵节等）
    const lunarFestivals = lunar.getFestivals();
    lunarFestivals.forEach((festival: string) => {
      festivals.push({
        id: `lunar_${currentDate.toISOString()}`,
        title: `${festival}营销活动`,
        date: currentDate.toISOString().split('T')[0],
        daysLeft: 0,
        type: "festival"
      });
    });

    // 获取节气信息（24节气）
    const jieQi = lunar.getJieQi();
    if (jieQi) {
      festivals.push({
        id: `jieqi_${currentDate.toISOString()}`,
        title: `${jieQi}营销活动`,
        date: currentDate.toISOString().split('T')[0],
        daysLeft: 0,
        type: "festival"
      });
    }

    // 获取公历节日（如元旦、圣诞节等）
    const solarFestivals = Lunar.Solar.fromDate(currentDate).getFestivals();
    solarFestivals.forEach((festival: string) => {
      festivals.push({
        id: `solar_${currentDate.toISOString()}`,
        title: `${festival}营销活动`,
        date: currentDate.toISOString().split('T')[0],
        daysLeft: 0,
        type: "festival"
      });
    });
  }
  return festivals;
};

/**
 * 营销模板数据
 * 包含两部分：
 * 1. 动态生成的节日营销活动（通过getNextMonthFestivals获取）
 * 2. 固定的重要营销节点（如618、双11等）
 */
const MARKETING_TEMPLATES: MarketingTemplate[] = [
  ...getNextMonthFestivals(),
  {
    id: "4",
    title: "618年中大促",
    date: "2025-06-18",
    daysLeft: 0,
    type: "promotion"
  },
  {
    id: "5",
    title: "双11购物节",
    date: "2025-11-11",
    daysLeft: 0,
    type: "promotion"
  },
  {
    id: "6",
    title: "圣诞跨年活动",
    date: "2025-12-24",
    daysLeft: 0,
    type: "festival"
  }
];

/**
 * 日历组件
 * 功能：
 * 1. 显示公历日期和农历日期
 * 2. 支持年月切换
 * 3. 显示节日和节气信息
 * 4. 右侧显示营销活动模板
 */
const Calendar: React.FC = () => {
  // 获取当前日期
  const today = new Date();
  // 状态管理：年份、月份和日历数据
  const [year, setYear] = useState(today.getFullYear());
  const [month, setMonth] = useState(today.getMonth());
  const [days, setDays] = useState<CalendarDay[]>([]);

  /**
   * 生成年份选择器的选项
   * 范围：当前年份前后5年
   */
  const yearOptions = Array.from({ length: 10 }, (_, i) => ({
    value: year - 5 + i,
    label: `${year - 5 + i}年`,
  }));

  /**
   * 生成月份选择器的选项
   * 范围：1-12月
   */
  const monthOptions = Array.from({ length: 12 }, (_, i) => ({
    value: i,
    label: `${i + 1}月`,
  }));

  /**
   * 获取指定日期的农历信息
   * @param date 公历日期
   * @returns 返回农历日期和节日信息
   */
  const getLunarInfo = (date: Date) => {
    const lunar = Lunar.Solar.fromDate(date).getLunar();
    const festivals: Festival[] = [];

    // 获取农历节日信息
    const lunarFestival = lunar.getFestivals();
    if (lunarFestival.length > 0) {
      festivals.push({
        name: lunarFestival[0],
        date: date.toISOString().split('T')[0],
        type: 'holiday',
        color: '#ff4d4f'
      });
    }

    // 获取节气信息
    const jieQi = lunar.getJieQi();
    if (jieQi) {
      festivals.push({
        name: jieQi,
        date: date.toISOString().split('T')[0],
        type: 'other',
        color: '#52c41a'
      });
    }

    // 获取公历节日信息
    const solarFestival = Lunar.Solar.fromDate(date).getFestivals();
    if (solarFestival.length > 0) {
      festivals.push({
        name: solarFestival[0],
        date: date.toISOString().split('T')[0],
        type: 'memorial',
        color: '#722ed1'
      });
    }

    return {
      lunarDate: lunar.getDayInChinese(), // 获取农历日期（如：初一、初二等）
      festivals
    };
  };

  /**
   * 初始化日历数据
   * 在年份或月份变化时重新计算日历数据
   */
  useEffect(() => {
    const monthDays = getMonthDays(year, month);
    // 为每一天添加农历和节日信息
    const daysWithLunar = monthDays.map(day => {
      const { lunarDate, festivals } = getLunarInfo(day.date);
      return {
        ...day,
        lunarDate,
        festivals
      };
    });
    setDays(daysWithLunar);
  }, [year, month]);

  /**
   * 计算指定日期距离今天的天数
   * @param date 目标日期（格式：YYYY-MM-DD）
   * @returns 返回距离今天的天数
   */
  const getDaysLeft = (date: string) => {
    const targetDate = new Date(date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const diffTime = targetDate.getTime() - today.getTime();
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  };

  /**
   * 获取未来的营销活动
   * 按照距离今天的天数排序
   * @returns 返回排序后的营销活动数组
   */
  const getFutureMarketingEvents = () => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    return MARKETING_TEMPLATES
      .filter(template => {
        const eventDate = new Date(template.date);
        return eventDate >= today;
      })
      .map(template => ({
        ...template,
        daysLeft: getDaysLeft(template.date)
      }))
      .sort((a, b) => a.daysLeft - b.daysLeft);
  };

  /**
   * 日历控制函数
   */
  // 返回今天
  const goToToday = () => {
    const today = new Date();
    setYear(today.getFullYear());
    setMonth(today.getMonth());
  };

  // 切换到上一个月
  const prevMonth = () => {
    if (month === 0) {
      setYear(year - 1);
      setMonth(11);
    } else {
      setMonth(month - 1);
    }
  };

  // 切换到下一个月
  const nextMonth = () => {
    if (month === 11) {
      setYear(year + 1);
      setMonth(0);
    } else {
      setMonth(month + 1);
    }
  };

  return (
    <div className={styles.calendarContainer}>
      <div className={styles.calendar}>
        <div className={styles.header}>
          <div className={styles.controls}>
            <Select
              value={year}
              options={yearOptions}
              onChange={(value) => setYear(value)}
              className={styles.yearSelect}
            />
            <div className={styles.monthControls}>
              <LeftOutlined onClick={prevMonth} />
              <Select
                value={month}
                options={monthOptions}
                onChange={(value) => setMonth(value)}
                className={styles.monthSelect}
              />
              <RightOutlined onClick={nextMonth} />
            </div>
            <button onClick={goToToday} className={styles.todayButton}>
              回到今天
            </button>
          </div>
        </div>

        <div className={styles.weekDays}>
          {["日", "一", "二", "三", "四", "五", "六"].map((day) => (
            <div key={day} className={styles.weekDay}>
              {day}
            </div>
          ))}
        </div>

        <div className={styles.days}>
          {days.map((day, index) => {
            // 判断是否为今天
            const isToday =
              day.day === today.getDate() &&
              day.month === today.getMonth() &&
              day.year === today.getFullYear();

            return (
              <div
                key={index}
                className={`${styles.day} ${!day.isCurrentMonth ? styles.otherMonth : ''} ${isToday ? styles.today : ''}`}
              >
                <div className={styles.dateRow}>
                  <span className={styles.dayNumber}>{day.day}</span>
                  <span className={styles.lunarDate}>{day.lunarDate}</span>
                </div>
                <div className={styles.festivalsContainer}>
                  {day.festivals.map((festival, idx) => (
                    <div
                      key={idx}
                      className={styles.festival}
                      style={{ color: festival.color }}
                    >
                      {festival.name}
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div className={styles.marketingTemplates}>
        <h3>营销模版直通车</h3>
        <div className={styles.templateList}>
          {getFutureMarketingEvents().map((template) => (
            <div key={template.id} className={styles.template}>
              <div className={styles.templateHeader}>
                <span className={styles.templateDate}>{template.date}</span>
                <span className={styles.daysLeft}>
                  还剩 {template.daysLeft} 天
                </span>
              </div>
              <div className={styles.templateTitle}>
                {template.title}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Calendar;
